<?php
$this_dir = dirname(__FILE__) . '/';
require_once($this_dir . '../plugin/autoload.php');

$uri = $_SERVER['REQUEST_URI'];
$rules = ConfLib::get('route', 'action');
function route($rules, $uri) {
    foreach($rules as $k=>$v) {
        if(1 === preg_match('/' . $k . '/', $uri)) {
            return $v;
        }
    }
    throw new HttpException('', 404);
}

try {
    $action_name = route($rules, $uri);
    $a = new $action_name ($uri);
    $r = $a->execute();
} catch (HttpException $e) {
    $r = $e->getData();
} catch (Exception $e) {echo 'Exception';
    throw new HttpException('', 400); //todo 这里throw，哪里catch
}

function getStatusStr($code) {
    //fastcgi与apache module不同
    //这里按照fastcgi格式
    //http://cn.php.net/manual/en/function.header.php
    $http_code_map = array(
        '200' => '200 OK',
        '202' => '202 Accepted',
        '301' => '301 Moved Permanently',
        '302' => '302 Found',
        '404' => '404 Not Found',
    );
    return 'Status: ' . $http_code_map[$code];
}
function output($r) {
    //fastcgi与apache module不同
    //这里按照fastcgi格式
    //http://cn.php.net/manual/en/function.header.php
    $status_str = getStatusStr($r['http']['status_code']);
    if(in_array($r['http']['status_code'], array(301, 302, 500))) {
        header('Location: ' . $r['http']['uri'], true, $r['http']['status_code']);
        exit;
    } else {
        header($status_str);
    }
    header('Content-Type: ' . $r['http']['content-type']);
    $tmp = array();
    foreach($r['http']['cache-control'] as $k=>$v) {
        if(is_numeric($k) && in_array($v, array('private', 'public', 'no-cache'))) {
            $tmp[] = $v;
            continue;
        }
        if($k == 'max-age') {
            $tmp[] = 'max-age=' . $v;
            continue;
        }
    }
    header('Cache-Control:' . implode(', ', $tmp));
    if(isset($r['http']['cache-control']['max-age'])) {
        header('Expires:' . gmdate('D, d M Y H:i:s T', time() + $r['http']['cache-control']['max-age']));
    }
    $v = $r['data'];
    switch($r['http']['content-type']) {
        case 'text/html' :
            $v['static_uri'] = ConfLib::get('static', 'uri');
            require dirname(__FILE__) . '/../view/default/'. $r['tpl'] . '.tpl';
            break;
        case 'text/plain' :
            echo $v;
            break;
        case 'application/json' :
            echo json_encode($v);
            break;
        case 'application/atom+xml' :
            //todo
            break;
    }
    return true;
}
output($r);
exit;
?>
